<template>
	<wsPage title="前端分类列表">
		<div slot="page_operate">
			<Button  @click="refresh">
                <Icon type="refresh"></Icon>
                <span>刷新</span>
            </Button>
		</div>
		<wsSmPanel>
			<div slot="list_operate">
				<Select class="ws-form-select" v-model="params.languageCode" @on-change="languageChange">
					<Option :value="item.code" v-for="item in fields.languages">{{item.motherTongue}}/{{item.english}}</Option>
				</Select>
				<Button  @click="showAddModal">添加分类</Button>
				<Button  @click="showUpModal">上线设置</Button>
			</div>
			<div slot="list_data">
				<Alert show-icon>
					操作提示
					<template slot="desc">
						<p>1.下线类目只影响APP类目显示，不影响商品搜索结果</p>
						<p>2.下线类目，其所有子类目都不显示</p>
						<p>3.最多支持三级目录</p>
					</template>
				</Alert>
				<div class="title-row">
					<span style="">当前路径:</span>
					<span v-for="(item, index) in history.parents">
						<span v-if="index > 0" style="padding: 0 3px;">></span>
					<a @click="listParent(item, index)" v-text="item.name"></a>
					</span>
				</div>
				<ws-table :data="table.data" style="width: 100%">
					<ws-table-column align="center" prop="name" label="名称">
						<template slot-scope="scope">
							<a @click="listChilds(scope.row)" v-if="scope.row.leafNodeType == 1">{{scope.row.name}}</a>
							<span v-if="scope.row.leafNodeType == 0" v-text="scope.row.name"></span>
						</template>
					</ws-table-column>
					<ws-table-column align="center" prop="fileId" label="LOGO" width="160">
						<template slot-scope="scope">
							<img :src="scope.row.logoImgUrl" style="width: 40px;height: 40px;" v-if="scope.row.logoImgUrl" />
						</template>
					</ws-table-column>
					<ws-table-column align="center" prop="childsNum" label="子类目" width="80"></ws-table-column>
					<!-- <ws-table-column align="center" label="状态" width="100">
						<template slot-scope="scope">
							<Tag color="red" v-if="scope.row.status == 0">已下线</Tag>
							<Tag color="blue" v-if="scope.row.status == 1">已上线</Tag>
						</template>	
					</ws-table-column> -->
					<ws-table-column align="center" prop="wDesc" label="描述" min-width="180"></ws-table-column>
					<ws-table-column align="center" width="120" label="操作">
						<template slot-scope="scope">
							<Button @click="showEditModal(scope.row)" type="text" size="small">编辑</Button>
							<Button @click="showTranslateModal(scope.row)" type="text" size="small">翻译</Button>
							<Button type="text" size="small" v-if="scope.row.leafNodeType == 0" @click="showSpecModal(scope.row)">聚合</Button>
							<Button @click="moveup(scope.row)" type="text" size="small" v-if="isSort && scope.$index != 0">上移</Button>
							<Button @click="movedown(scope.row)" type="text" size="small" v-if="isSort && scope.$index != table.data.length - 1">下移</Button>
						</template>
					</ws-table-column>
				</ws-table>
			</div>
		</wsSmPanel>

		<!--新增属性弹框-->
		<wsModal v-model="modal.show" ok-text="保存" :title="modal.title" @on-ok="modalSave" @on-cancel="modalCancel">
			<Form ref="modalForm" :model="modal.form" :rules="modal.validate" :label-width="100">
				<FormItem label="父类目" required>
					<span v-text="parentPath"></span>
				</FormItem>
				<FormItem label="名称" prop="name">
					<Input v-model="modal.form.name" autofocus></Input>
				</FormItem>
				<FormItem label="LOGO" prop="logo">
					<ws-upload-cos ref="upload" catelog="app-category" :cfile-key="modal.fileKey" :show-upload-list="false" :format="['jpg','jpeg','png']" :max-size="2048" :on-success="logoUploadSuccess" type="drag" style="display: inline-block;width:60px;">
						<div style="width: 60px;height:60px;line-height: 60px;">
							<img :src="modal.form.logoImgUrl" width="60px" height="60px" v-if="modal.form.logoImgUrl"></img>
						</div>
					</ws-upload-cos>
				</FormItem>
				<FormItem label="允许子类目" prop="leafNodeType" v-if="!isEdit" v-show="controlcategoryshow" required>
					<i-switch v-model="modal.fields.leafNodeType"></i-switch>
				</FormItem>
				<FormItem label="描述" prop="wDesc">
					<Input v-model="modal.form.wDesc" type="textarea"></Input>
				</FormItem>
			</Form>
		</wsModal>

		<!--规格参数模态框-->
		<wsModal v-model="modal1.show" :width="640" hide-footer ok-text="保存" :title="modal1.title" @on-ok="modal1Save" @on-cancel="modal1Cancel">
			<div>
				<Row class="title-row">
					<Col span="12" style="padding-right:10px">
					<Cascader :data="modal1.table.categorys" v-model="modal1.table.categoryIds"></Cascader>
					</Col>
					<Col span="12" style="padding-right:10px">
					<Button @click="categoryAggregation">添加</Button>
					</Col>
				</Row>
				<ws-table :data="modal1.table.data" style="width: 100%">
					<ws-table-column align="center" prop="categoryPath" label="类目"></ws-table-column>
					<ws-table-column align="center" width="80" label="操作">
						<template slot-scope="scope">
							<Button type="text" size="small" @click="delCategoryAggregate(scope.row)">删除</Button>
						</template>
					</ws-table-column>
				</ws-table>
			</div>
		</wsModal>
		<!--上线类目设置-->
		<wsModal v-model="modal2.show" :width="640" ok-text="保存" title="上线类目设置" @on-ok="modal2Save" @on-cancel="modal2Cancel">
			<div>
				<Tree :data="modal2.tree.data" show-checkbox multiple ref="tree"></Tree>
			</div>
		</wsModal>

		<!--翻译内容弹框-->
		<wsModal v-model="modal3.show" ok-text="保存" title="类目翻译"  @on-ok="modal3Save"  @on-cancel="modal3Cancel">
		    <Form ref="modal3Form" :model="modal3.model" :rules="modal3.rules" :label-width="100">
		        <FormItem label="英文(en)" prop="name">
		            <Input  v-model="modal3.model.name"></Input>
		        </FormItem>
				<FormItem label="繁体(cht)" prop="name">
		            <Input  v-model="modal3.model.name2"></Input>
		        </FormItem>
		    </Form>	
		</wsModal>	
	</wsPage>
</template>

<script>
	import Util from '../../../common/util.js';
	import Common from '../../../common/common.js';
	export default {
		data() {
			return {
				controlcategoryshow: false,
				params: {
					parentId: -1,
					languageCode: 'zh', //当前选中的langaugeCode
				},
				fields: {
					languages: [] //翻译语言列表
				},
				table: {
					data: [],
					editRow: null //当前编辑项
				},
				history: {
					pages: [],
					parents: [{
						name: '首页',
						id: -1
					}]
				},
				modal: {
					show: false,
					title: '',
					form: {
						id: '',
						languageCode: 'zh', //当前选中的langaugeCode
						name: '',
						leafNodeType: 1,
						wDesc: '',
						logoImgUrl: ''
					},
					fileKey: '',
					fields: {
						leafNodeType: true
					},
					validate: {
						name: [{
							required: true,
							message: '名称不能为空',
							trigger: 'blur'
						}]
					}
				},
				//规格参数
				modal1: {
					show: false,
					title: '',
					form: {
						aggregateType: 2, //聚合类型 1 商铺 2商品分类 3商品 0不聚合
					},
					table: { //类目
						categoryIds: [], //当前选中的服务目录编号
						categorys: [], //服务目录
						data: []
					}
				},
				modal2: {
					show: false,
					tree: {
						data: [{
							// id:'',
							// name:'',
							// parentId:'',
							// children:'',
							title: '',
							checked: true,
							expand: true,
							selected: true
						}]
					}
				},
				modal3: {
					show: false,
					table: {
						datas: []
					},
					model: {
						appCategoryId: '',
						name: '',
						name2: '',
					},
					rules: {
						name: [{ required: true, message: '名称不能为空'}],
						name2: [{ required: true, message: '名称不能为空'}]
					}
				}
			}
		},
		computed: {
			isEdit() {
				return !Util.vad.isBlank(this.modal.form.id);
			},
			/**
			 * 父路径
			 */
			parentPath() {
				let parents_ = this.history.parents;
				let r = '';
				for(let i = 0; i < parents_.length; i++) {
					if(0 != i) {
						r += '>';
					}
					r += parents_[i].name;
				}
				return r;
			},
			/**
			 * 是否可以排序,当列表长度大于1的时候
			 */
			isSort() {
				return this.table.data.length > 1;
			}
		},
		mounted() {
			this.init();
		},
		methods: {
			init() {
				this.initLanguages();
				this.query();
				this.initCategorys();
			},
			/**
			 * 加载翻译语言列表
			 */
			initLanguages() {
				const _this = this;
				this.axios.get('/ws/ops/v2/languages/translatable').then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if(0 == resMeta.code) {
						_this.fields.languages = res.data;
					} else {
						_this.$Message.warning(resMeta.message);
					}
				});
			},

			/**
			 * 显示翻译
			 */
			showTranslateModal(row_) {
				const _this = this;
				this.modal3.model.appCategoryId = row_.id;
				this.axios.get('/ws/ops/v2/app/category/translates/' + row_.id).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.buildTranslateData(res.data);
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('加载翻译内容失败:' + message_);
					}
				});
				
			},
			buildTranslateData(data) {
				this.modal3.table.datas = data;
				//目录只处理英文，后面可以直接变成表格形式
				for(let i = 0; i < data.length; i++) {
					let tdata = data[i];
					if(tdata.languageCode == 'en') {
						this.modal3.model.name = tdata.name;
					}else if(tdata.languageCode == 'cht'){
						this.modal3.model.name2 = tdata.name;
					}
					
				}
				this.modal3.show = true;
			},

			/**
			 * 翻译框保存操作
			 */
			modal3Save() {
				this.$refs['modal3Form'].validate((valid) => {
					if (valid) {
						this.submitModal2();
						this.submitModal3();
					} 
				});
			},

			/**
			 * 保存模态框
			 */
			submitModal2() {
				const _this = this;
				let postData_ = {
					appCategoryId: this.modal3.model.appCategoryId,
					name: this.modal3.model.name,
					languageCode: 'en'
				}
				this.axios.put('/ws/ops/v2/app/category/translates', postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success('添加商品类目翻译成功');
						_this.modal2Cancel();
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('添加商品类目翻译失败:' + message_);
					}
				});				
			},


			/**
			 * 保存模态框2
			 */
			submitModal3() {
				const _this = this;
				let postData_ = {
					appCategoryId: this.modal3.model.appCategoryId,
					name: this.modal3.model.name2,
					languageCode: 'cht'
				}
				this.axios.put('/ws/ops/v2/app/category/translates', postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						//_this.$Message.success('添加商品类目翻译成功');
						_this.modal3Cancel();
					} else {
						let message_ = res.meta.message;
						//_this.$Message.warning('添加商品类目翻译失败:' + message_);
					}
				});				
			},
			modal3Cancel() {
				this.modal3.model.name = '';
				this.modal3.model.name2 = '';
				this.$refs['modal3Form'].resetFields();
				this.modal3.show = false;
			},
			/**
			 * 选中语言发生变化
			 */
			languageChange(val) {
				this.params.parentId = -1;
				this.history.pages = [];
				this.history.parents = [{
					name: '首页',
					id: -1
				}];
				this.query();
			},
			/**
			 * 初始化分类树结构
			 */
			initappCategories() {
				let _this = this;
				let languageCode = this.params.languageCode;
				this.axios.get('/ws/ops/v2/app/categorys/tree/' + languageCode).then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if(0 == resMeta.code) {
						_this.modal2.tree.data = res.data.children;
						_this.modal2.show = true;
						// this.modal2.tree.data.title = res.data.children.name;
					} else {
						_this.$Message.warning(resMeta.message);
					}
				});
			},
			//修改分类status
			modal2Save() {
				// debugger;
				// console.log(this.$refs.tree.getCheckedNodes())
				let postData_ = this.$refs.tree.getCheckedNodes();
				let languageCode = this.params.languageCode;
				const _this = this;
				this.axios.put('/ws/ops/v2/app/category/status/' + languageCode, postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success('前端类目上下线状态修改成功');
						_this.init();
						_this.modal2.show = false;
					} else {
						_this.$Message.warning('前端类目上下线状态修改失败');
					}
				});
			},
			modal2Cancel() {
				this.modal2.show = false;
			},
			moveup(rowData) {
				this.modal.form.flag = "up";
				this.modal.form.id = rowData.id;
				this.modal.form.parentId = this.params.parentId;
				this.updown();
			},
			movedown(rowData) {
				this.modal.form.flag = "down";
				this.modal.form.id = rowData.id;
				this.modal.form.parentId = this.params.parentId;
				this.updown();
			},
			updown() {
				let postData_ = this.modal.form;
				const _this = this;
				this.axios.put('/ws/ops/v2/app/appcategory/move', postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success('上移或下移操作成功');
						_this.init();
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('上移或下移操作失败:' + message_);
					}
				});
			},
			refresh() {
				this.query();
			},
			/**
			 * 查看列表
			 */
			query() {
				let parentId = this.params.parentId;
				let languageCode = this.params.languageCode;
				const _this = this;
				this.axios.get('/ws/ops/v2/app/categorys/' + parentId + '/' + languageCode).then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if(0 == resMeta.code) {
						_this.buildPageData(res.data);
					} else {
						_this.$Message.warning(resMeta.message);
					}
				});
			},
			/**
			 * 构建页面数据
			 */
			buildPageData(data_) {
				this.table.data = data_;
			},
			/**
			 * 获取子列表
			 */
			listChilds(row_) {
				this.history.parents.push({
					name: row_.name,
					id: row_.id
				});
				this.params.parentId = row_.id;
				this.query();
			},
			/**
			 * 列出父节点
			 */
			listParent(item_, index_) {
				//如果已经是最后了，就不用显示
				let parentLength = this.history.parents.length;
				if(index_ == parentLength - 1) {
					return;
				}
				//从数组中截掉
				this.params.parentId = item_.id;
				this.history.parents.splice(index_ + 1, parentLength - index_ - 1);
				this.query();
			},
			/**
			 * 重置模态框1
			 */
			resetModalForm() {
				this.$refs['modalForm'].resetFields();
				this.modal.form.id = '';
				this.modal.form.name = '';
				this.modal.form.leafNodeType = 1;
				this.modal.form.wDesc = '';
				this.modal.form.logoImgUrl = '';
				this.modal.fileKey = '';
				this.modal.fields.leafNodeType = true;
				this.controlcategoryshow = false;
				this.modal.fields.leafNodeType = true;
			},
			/**
			 * 显示添加模态框1
			 */
			showAddModal() {
				let _this = this;
				this.modal.title = '新增前端类目';
				this.modal.show = true;
				//二级目录的parentId的parentId为-1就显示，其他隐藏
				// this.modal.form.parentId = this.params.parentId;
				//this.modal.form.id = rowData.id;
				let flag = this.history.parents.length;
				if(flag === 2) {
					this.controlcategoryshow = true;
				}
				if(flag === 3) {
					this.modal.form.leafNodeType = 0;
					this.modal.fields.leafNodeType = false;
				}
			},
			/**
			 * 模态框保存
			 */
			modalSave() {
				this.$refs['modalForm'].validate((valid) => {
					if(valid) {
						if(!this.modal.fields.leafNodeType && Util.vad.isBlank(this.modal.form.logoImgUrl)) {
							this.$Message.info('必须设置分类的LOGO');
							return;
						}
						this.submitModal();
					}
				});
			},
			/**
			 * 提交模态框事件
			 */
			submitModal() {
				let isLeafNodeType = this.modal.fields.leafNodeType;
				this.modal.form.leafNodeType = isLeafNodeType ? 1 : 0;
				this.modal.form.languageCode = this.params.languageCode;
				if(this.isEdit) {
					this.editModal();
				} else {
					this.saveModal();
				}
			},
			/**
			 * 保存模态框
			 */
			saveModal() {
				let postData_ = this.modal.form;
				const _this = this;
				let parentId = this.params.parentId;
				postData_.parentId = parentId;
				this.axios.post('/ws/ops/v2/app/category', postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success('新增前端类目成功');
						_this.modalCancel();
						_this.init();
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('新增商品类目失败:' + message_);
					}
				});
			},
			/**
			 * 修改模态框
			 */
			editModal() {
				let postData_ = this.modal.form;
				const _this = this;
				this.axios.put('/ws/ops/v2/app/category', postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success('修改前端类目成功');
						_this.modalCancel();
						_this.init();
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('修改前端类目失败:' + message_);
					}
				});
			},
			/**
			 * 模态框取消
			 */
			modalCancel() {
				this.resetModalForm();
				this.modal.show = false;
			},
			/**
			 * 打开新增模态框
			 */
			showEditModal(rowData) {
				this.modal.title = '修改前端类目';
				this.initModalData(rowData.id);
			},
			/**
			 * 初始化模态框数据
			 */
			initModalData(categoryId) {
				let _this = this;
				this.axios.get('/ws/ops/v2/app/category/' + categoryId).then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if(0 == resMeta.code) {
						_this.buildModalData(res.data);
					} else {
						_this.$Message.warning(resMeta.message);
					}
				});
			},
			/**
			 * 构建模态框的图片
			 */
			buildModalData(data) {
				this.modal.form.id = data.id;
				this.modal.form.name = data.name;
				this.modal.form.aggregateType = data.aggregateType;
				this.modal.form.wDesc = data.wDesc;
				this.modal.form.leafNodeType = data.leafNodeType;
				this.modal.form.logoImgUrl = data.logoImgUrl;
				this.modal.fields.leafNodeType = (data.leafNodeType == 1 ? true : false);

				this.modal.show = true;
			},
			/**
			 * 显示规格模态框
			 */
			showSpecModal(row_) {
				this.table.editRow = row_;
				this.modal1.show = true;
				this.modal1.title = '聚合商品类目操作';
				this.initCategoryAggregates();
			},
			/**
			 * 模态框1保存
			 */
			modal1Save() {
				this.modal1Cancel();
			},
			/**
			 * 模态框1取消
			 */
			modal1Cancel() {
				this.modal1.show = false;
				this.modal1.table.categoryId = '';
			},
			/**
			 * LOGO上传成功
			 */
			logoUploadSuccess(response, file, fileList) {
				if(0 == response.meta.code) {
					this.modal.form.logoImgUrl = response.data.pubFileUrl;
					this.modal.fileKey = response.data.fileId;
				}
			},
			/**
			 * 初始化目录列表(商品)
			 */
			initCategorys() {
				let _this = this;
				this.axios.get('/ws/ops/v2/categorys/tree').then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if(0 == resMeta.code) {
						_this.buildProductCategorys(res.data);
					} else {
						_this.$Message.warning(resMeta.message);
					}
				});
			},
			buildProductCategorys(datas) {
				let categorys = this.modal1.table.categorys;
				for(let i = 0; i < datas.length; i++) {
					categorys.push(datas[i]);
				}
			},
			/**
			 * 商品类目聚合
			 */
			categoryAggregation() {
				let values = this.modal1.table.categoryIds;
				let appCategoryId = this.table.editRow.id;
				let postData_ = {
					appCategoryId: appCategoryId,
					relationId: values[values.length - 1],
					type: 2
				};
				const _this = this;
				this.axios.put('/ws/ops/v2/app/category/aggregate', postData_).then(function(response) {
					let res = response.data;
					if(0 === res.meta.code) {
						_this.$Message.success('添加聚合类目成功');
						_this.modal1.table.categoryIds = [];
						_this.initCategoryAggregates();
					} else {
						let message_ = res.meta.message;
						_this.$Message.warning('添加聚合类目失败:' + message_);
					}
				});
			},
			/**
			 * 初始化聚合类目
			 */
			initCategoryAggregates() {
				let _this = this;
				let categoryId = this.table.editRow.id;
				this.axios.get('/ws/ops/v2/app/category/aggregate/' + categoryId).then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if(0 == resMeta.code) {
						_this.buildCategoryAggregateData(res.data);
					} else {
						_this.$Message.warning(resMeta.message);
					}
				});
			},
			/**
			 * 构建目录聚合项
			 */
			buildCategoryAggregateData(data) {
				this.modal1.table.data = data;
			},
			/**
			 * 删除目录聚合项目
			 */
			delCategoryAggregate(row) {
				let aggregateId = row.aggregateId;
				let _this = this;
				this.axios.delete('/ws/ops/v2/app/category/aggregate/' + aggregateId).then(response => {
					var res = response.data;
					var resMeta = res.meta;
					if(0 == resMeta.code) {
						_this.initCategoryAggregates();
						_this.$Message.info('删除聚合项成功');
					} else {
						_this.$Message.warning(resMeta.message);
					}
				});
			},
			/**
			 * 上线设置
			 */
			showUpModal() {
				this.initappCategories();
			}
		}
	}
</script>

<style scoped>
	.ws-form-select {
		width: 162px;
	}
	
	.title-row {
		padding: 10px;
	}
</style>